#include "readthread.h"
#include <errno.h>
//#define DEBUG
ReadThread::ReadThread(int serialFD) : QThread(), m_serial(serialFD)
{
    m_index = 0;
    m_data = NULL;
}

ReadThread::~ReadThread()
{
    if(m_data != NULL)
	delete[] m_data;
    ::close(m_serial);
}

void ReadThread::run()
{
    struct timeval timeout;
    int fd_num;
    int usedLen;
    
    
    while(1)
    {
	FD_ZERO(&m_readSet);
	FD_SET(m_serial,&m_readSet);
	timeout.tv_sec = 0;
	timeout.tv_usec = 500;
	
	fd_num = select(m_serial + 1, &m_readSet, NULL, NULL, &timeout);


        switch(fd_num)
        {
        case 0:
            break;
        case -1:
            qDebug("errno = %d",errno);
            break;
        default:
            if(FD_ISSET(m_serial,&m_readSet))
            {
                if(ioctl(m_serial, FIONREAD, &m_aviLen) < 0)
                {
                    #ifdef DEBUG
                    qDebug("ioctl(m_serial, FIONREAD, &m_aviLen) < 0 Error %s\n",strerror(errno));
                    #endif
                    return;
                }

                if(m_aviLen > 0)
                {
                    if(m_aviLen > BUFFERLEN)
                    {
                        #ifdef DEBUG
                        qDebug("overflow");
                        #endif
                        tcflush(m_serial,TCIOFLUSH);
                        ioctl(m_serial,FIONREAD,&m_aviLen);
                        usedLen = 0;
                    }
                    else
                    {
                        usedLen = read(m_serial,m_recvBuf+m_index,m_aviLen);
                       // m_index += usedLen;
                      //  if(m_data != NULL)
                       //     delete[] m_data;
                       // m_data = new char[m_index];
                       // memcpy(m_data,m_recvBuf,m_index);
                       // emit ReceivedData(m_data,m_index);
                        emit ReceivedData(m_recvBuf,usedLen);
                        m_index = 0;
                    }
                }
            }
            break;
        }

    }
    exec();
}
